package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.JwtHelper;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/api/ucenter/wx")
@Controller
public class WxApiController {
    @Autowired
    UserInfoService userInfoService;
    @ResponseBody
    @GetMapping("/getLoginParam")
    public R getLoginParam() throws UnsupportedEncodingException {
        Map<String,Object> map=new HashMap<>();
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
        map.put("redirectUri",redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return R.ok().data(map);
    }

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) throws Exception {
        //得到授权临时票据code
        StringBuffer stringBuffer = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(stringBuffer.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        UserInfo userInfo =userInfoService.selectWxInfoOpenId(openid);
        if (userInfo==null){
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String format = String.format(baseUserInfoUrl, access_token, openid);
            String userInfoUrl = HttpClientUtils.get(format);
            JSONObject object = JSONObject.parseObject(userInfoUrl);
            String nickname = object.getString("nickname");
            //用户头像
            String headimgurl = object.getString("headimgurl");
            userInfo=new UserInfo();
            userInfo.setOpenid(openid);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }
        Map<String,String> map=new HashMap<>();
        if (StringUtils.isEmpty(userInfo.getPhone())){
            map.put("openid",userInfo.getOpenid());
        }else {
            map.put("openid","");
        }
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        return "redirect:http://localhost:3000/weixin/callback?token="+token+"&name="+URLEncoder.encode(name,"utf-8")+"&openid="+map.get("openid");
    }
}
